package com.itheima.netmarket.impl.view;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.itheima.netmarket.GlobalConstants;
import com.itheima.netmarket.domain.Product;
import com.itheima.netmarket.impl.view.manager.UIManagerImpl;
import com.itheima.netmarket.utils.PromptManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.image.SmartImage;
import com.loopj.android.image.SmartImageView;
import com.loopj.android.image.WebImage;
import comitheima.netmarket.R;

/**
 * 支付中心主页
 * 
 * @author yangxin
 */
public class PayCenterView extends MainView implements OnClickListener {

	/**
	 * 头部返回键
	 */
	private TextView headBackText;
	/**
	 * 头部提交订单
	 */
	private TextView ordrSubmitTopText;
	/**
	 * 收货人信息
	 */
	private RelativeLayout paymentAddressRel;
	/**
	 * 支付方式
	 */
	private RelativeLayout paymentPayTypeRel;
	/**
	 * 送货时间选择
	 */
	private RelativeLayout paymentSendTimeRel;
	/**
	 * 送货方式选择
	 */
	private RelativeLayout paymentSendTypeRel;
	/**
	 * 使用优惠劵
	 */
	private RelativeLayout paymentRemarkRel;
	/**
	 * 索要发票
	 */
	private RelativeLayout paymentInvoiceRel;
	/**
	 * 提交订单
	 */
	private TextView ordrSubmitBottomText;
	/**
	 * 快递方式条目
	 */
	private final String[] items = { "快递", "EMS", "平邮" };
	/**
	 * 显示快递方式
	 */
	private TextView paymentSendTypeHintText;
	/**
	 * 选择快递的下标
	 */
	private int selected;

	/**
	 * 商品详情list
	 */
	private ListView paymentProductList;
	private ProductListAdapter adapter;

	/**
	 * 商品集合
	 */
	private List<Product> productList = new ArrayList<Product>();
	/**
	 * 显示优惠项目
	 */
	private RelativeLayout paymentContRel;
	/**
	 * 优惠具体显示条目
	 */
	private TextView paymentHintText;
	private TextView paymentShow;
	/**
	 * 显示支付方式
	 */
	private TextView payHintText;
	/**
	 * 显示发票内容
	 */
	private TextView invoiceHintText;
	/**
	 * 显示送货时间
	 */
	private TextView paymentSendTimeHintText;

	public PayCenterView(Context context) {
		super(context);
	}

	public PayCenterView(Context context, Bundle bundle) {
		super(context, bundle);
	}

	@Override
	public View getmView() {
		View view = View.inflate(context, R.layout.payment_center_activity, null);
		init(view);

		return view;
	}

	/**
	 * 初始化数据
	 */
	private void init(View view) {
		headBackText = (TextView) view.findViewById(R.id.head_back_text);
		ordrSubmitTopText = (TextView) view.findViewById(R.id.ordr_submit_top_text);
		paymentAddressRel = (RelativeLayout) view.findViewById(R.id.payment_address_rel);
		paymentPayTypeRel = (RelativeLayout) view.findViewById(R.id.payment_payType_rel);
		paymentSendTimeRel = (RelativeLayout) view.findViewById(R.id.payment_sendTime_rel);
		paymentSendTypeRel = (RelativeLayout) view.findViewById(R.id.payment_sendType_rel);
		paymentRemarkRel = (RelativeLayout) view.findViewById(R.id.payment_remark_rel);
		paymentInvoiceRel = (RelativeLayout) view.findViewById(R.id.payment_invoice_rel);
		ordrSubmitBottomText = (TextView) view.findViewById(R.id.ordr_submit_bottom_text);
		paymentSendTypeHintText = (TextView) view.findViewById(R.id.payment_sendTypeHint_text);
		paymentContRel = (RelativeLayout) view.findViewById(R.id.payment_cont_rel);
		paymentHintText = (TextView) view.findViewById(R.id.payment_Hint_text);
		paymentShow = (TextView) view.findViewById(R.id.payment_show);
		payHintText = (TextView) view.findViewById(R.id.payment_payHint_text);
		invoiceHintText = (TextView) view.findViewById(R.id.payment_invoiceHint_text);
		paymentSendTimeHintText = (TextView) view.findViewById(R.id.payment_sendTimeHint_text);

		paymentProductList = (ListView) view.findViewById(R.id.payment_product_list);

		setOnclick();
		getNetData();

		adapter = new ProductListAdapter();
		paymentProductList.setAdapter(adapter);

		paymentShow.setVisibility(View.GONE);
		paymentContRel.setVisibility(View.GONE);
		if (!TextUtils.isEmpty(GlobalConstants.paymentRemarkContent)) {
			paymentShow.setVisibility(View.VISIBLE);
			paymentContRel.setVisibility(View.VISIBLE);
			paymentHintText.setText(GlobalConstants.paymentRemarkContent);
		}
		if (!TextUtils.isEmpty(GlobalConstants.sendTimeContent)) {
			paymentSendTimeHintText.setText("送货时间：" + GlobalConstants.sendTimeContent);
		}
		if (!TextUtils.isEmpty(GlobalConstants.invoiceContent)) {
			invoiceHintText.setText("发票：" + GlobalConstants.invoiceContent);
		}
		if (!TextUtils.isEmpty(GlobalConstants.payTypeContent)) {
			payHintText.setText("支付方式：" + GlobalConstants.payTypeContent);
		}
		if (!TextUtils.isEmpty(GlobalConstants.SendTypeContent)) {
			paymentSendTypeHintText.setText("送货方式：" + GlobalConstants.SendTypeContent);
		}
	}

	/**
	 * 设置点击事件
	 */
	private void setOnclick() {
		headBackText.setOnClickListener(this);
		ordrSubmitTopText.setOnClickListener(this);
		paymentAddressRel.setOnClickListener(this);
		paymentPayTypeRel.setOnClickListener(this);
		paymentSendTimeRel.setOnClickListener(this);
		paymentSendTypeRel.setOnClickListener(this);
		paymentRemarkRel.setOnClickListener(this);
		paymentInvoiceRel.setOnClickListener(this);
		ordrSubmitBottomText.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.head_back_text:
			// 头部返回键
			UIManagerImpl.getInstance().pressBack();
			break;
		case R.id.ordr_submit_top_text:
			// 头部提交订单，支付去
			break;
		case R.id.payment_address_rel:
			// 收货人信息，选填地址
			break;
		case R.id.payment_payType_rel:
			// 支付方式
			UIManagerImpl.getInstance().changeView(PayTypeView.class);
			break;
		case R.id.payment_sendTime_rel:
			// 送货时间选择
			UIManagerImpl.getInstance().changeView(SendTimeView.class);
			break;
		case R.id.payment_sendType_rel:
			// 送货方式选择
			AlertDialog.Builder builder = new Builder(context);
			builder.setTitle("选择送货方式");
			builder.setSingleChoiceItems(items, selected, this);
			builder.setPositiveButton("确定", this);
			builder.show();
			break;
		case R.id.payment_remark_rel:
			// 使用优惠劵
			UIManagerImpl.getInstance().changeView(PaymentRemarkView.class);
			break;
		case R.id.payment_invoice_rel:
			// 索要发票
			UIManagerImpl.getInstance().changeView(InvoiceView.class);
			break;
		case R.id.ordr_submit_bottom_text:
			// 提交订单
			// TODO 判断、数据的封装
			// 判断提交订单前的必要信息是否填写完毕--收货地址、支付方式
			new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					// TODO 提交订单提示
					PromptManager.showProgressDialog(context);
				}

				@Override
				protected Void doInBackground(Void... params) {
					// TODO 数据封装存数据库
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					// TODO 页面跳转
					PromptManager.closeProgressDialog();
				}
			};
			break;
		}
	}

	/**
	 * 获取网络数据
	 */
	private void getNetData() {
		AsyncHttpClient client = new AsyncHttpClient();
		String url = "http://192.168.1.102:8080/NetMarketServer/checkout";
		RequestParams params = new RequestParams();
		params.put("sku", "1102539");
		client.post(url, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				Toast.makeText(context, "处理失败", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onSuccess(String content) {
				try {
					JSONObject object = new JSONObject(content);
					String string = object.getString("productlist");
					productList = JSON.parseArray(string, Product.class);
					adapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case DialogInterface.BUTTON_POSITIVE:
			GlobalConstants.SendTypeContent = items[selected];
			paymentSendTypeHintText.setText("送货方式：" + GlobalConstants.SendTypeContent);
			break;
		default:
			selected = which;
			break;
		}
	}

	/**
	 * 商品详情适配器
	 */
	private class ProductListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return productList.size();
		}

		@Override
		public Object getItem(int position) {
			return productList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = View.inflate(context, R.layout.product_listitem, null);

				holder.prodImageImg = (SmartImageView) convertView.findViewById(R.id.pro_item_prodImage_img);
				holder.ProdNameText = (TextView) convertView.findViewById(R.id.product_item_prodName_text);
				holder.prodColorText = (TextView) convertView.findViewById(R.id.pro_item_prodColor_text);
				holder.prodSizeText = (TextView) convertView.findViewById(R.id.pro_item_prodSize_text);
				holder.prodPriceText = (TextView) convertView.findViewById(R.id.pro_item_prodPrice_text);
				holder.prodCountText = (TextView) convertView.findViewById(R.id.pro_item_prodCount_text);
				holder.subtotalText = (TextView) convertView.findViewById(R.id.pro_item_subtotal_text);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Product product = productList.get(position);

			SmartImage image = new WebImage(product.getPic());
			holder.prodImageImg.setImage(image);
			holder.ProdNameText.setText(product.getName());
			holder.prodColorText.setText(null);
			holder.prodSizeText.setText(null);
			holder.prodPriceText.setText(String.valueOf(product.getPrice()));
			holder.prodCountText.setText(String.valueOf(12));
			holder.subtotalText.setText(String.valueOf(product.getPrice() * 12));

			return convertView;
		}
	}

	static class ViewHolder {
		/**
		 * 商品图片
		 */
		SmartImageView prodImageImg;
		/**
		 * 商品名称
		 */
		TextView ProdNameText;
		/**
		 * 商品颜色
		 */
		TextView prodColorText;
		/**
		 * 商品尺码
		 */
		TextView prodSizeText;
		/**
		 * 商品价格
		 */
		TextView prodPriceText;
		/**
		 * 商品数量
		 */
		TextView prodCountText;
		/**
		 * 小计
		 */
		TextView subtotalText;
	}

}
